/**
 * Filename: GAGameStateManager.js
 * Author: Abid Hussain
 * DateCreated: 15/07/2011
 */
exports.GAGameStateManager = Core.Class.singleton({
	initialize: function(){
		this._timeOut = 10;
		this._dbFiles = null;
		this._level = 1;
		this._localXP = 0;
		this._savedXP = 0;
		this._getSaveXpKey();
	},
	startTimer: function(timeOut){
		this._timeOut = timeOut;
		this._storage = new Storage.KeyValue();
		setTimeout(this._getSavedXp.bind(this),this._timeOut*1000);
	},
	setDelegate: function(delegate){
		this._delegate = delegate;
	},
	_getSaveXpKey: function(){
		this._saveXpKey = GAConfigurations.getGameCode()+GAConfigurations.getRecordID()+kGAGameState.kLastSavedXp;
	},
	_getConfigParams: function(){
		this._dbFiles = GAConfigurations.getDbFileNames();
		this._level = GAConfigurations.getGameLevel();
		this._localXP = GAConfigurations.getGameXp();
	},
	_getSavedXp: function(){
		this._storage.getItem(this._saveXpKey,this._getSavedXpCallback.bind(this));
	},
	_getSavedXpCallback: function(error,value,key){
		if(!error){
			this._savedXP = value;
		}
		this._getConfigParams();
		if(this._localXP > this._savedXP){
			this._postState();
		}
		else{
			this.startTimer(kGAGameState.kTimeOut);
		}
		console.log('>>_getSavedXpCallback :: localXP = '+this._localXP+' and saveXP = '+this._savedXP);
	},
	_postState: function(){
		GAGameStatePostHandler.postGameState(this,this._dbFiles,this._level,this._localXP);
	},
	gameStatePostSuccess: function(statusCode){
	console.log('>>gameStatePostSuccess ... '+statusCode);
		if(statusCode == 0){
			this._delegate.restartGame();
		}
		else{
			this._saveCurrentXp();
		}
	},
	gameStatePostFailure: function(error){
		console.log('>>gameStatePostFailure ...'+error);
		this.startTimer(kGAGameState.kTimeOut);
	},
	_saveCurrentXp: function(){
		this._storage.setItem(this._saveXpKey,this._localXP,this._savedXPCallback.bind(this));
	},
	_savedXPCallback: function(){
		this.startTimer(kGAGameState.kTimeOut);
	},
	
	destroy: function(){
		this._delegate = null;
		this._timeOut = null;
		this._dbFiles = null;
		this._level = null;
		this._localXP = null;
		this._savedXP = null;
		this._storage = null;
		this._saveXpKey = null;
	}
});